package com.iwdnb.gkgz.common.quota;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

import com.alibaba.fastjson.JSONObject;

import com.iwdnb.gkgz.common.model.dto.StockDayData;
import com.iwdnb.gkgz.common.utils.BigDecimalUtils;

/**
 * 计算移动均线
 */
public class MovingAverage {

    public static void calculateEMA(List<StockDayData> stockDayDataList, List<Integer> periods) {
        calculateEMA(stockDayDataList, periods, false);
    }

    public static void calculateEMA(List<StockDayData> stockDayDataList, List<Integer> periods, boolean useMinPrice) {
        for (Integer period : periods) {
            calculateEMA(stockDayDataList, period, useMinPrice);
        }
    }

    public static void calculateEMA(List<StockDayData> stockDayDataList, Integer period) {
        calculateEMA(stockDayDataList, period, false);
    }

    public static void calculateEMA(List<StockDayData> stockDayDataList, Integer period, boolean useMinPrice) {
        double[] prices = new double[stockDayDataList.size()];
        for (int i = 0; i < stockDayDataList.size(); i++) {
            if (useMinPrice) {
                prices[i] = stockDayDataList.get(i).getMinPrice().doubleValue();
            } else {
                prices[i] = stockDayDataList.get(i).getClosePrice().doubleValue();

            }
        }
        double[] datas = calculateEMA(prices, period);
        for (int i = 0; i < stockDayDataList.size(); i++) {
            StockDayData stockDayData = stockDayDataList.get(i);
            JSONObject average = stockDayData.getAvarage();
            if (Objects.isNull(average)) {
                average = new JSONObject();
            }
            average.put(period.toString(), BigDecimalUtils.round(new BigDecimal(datas[i])));
            stockDayData.setAvarage(average);
        }
    }

    // 计算指数移动平均线（EMA）
    public static double[] calculateEMA(double[] prices, int period) {
        double[] ema = new double[prices.length];
        ema[0] = prices[0]; // 第一个EMA值作为起始点
        for (int i = 0; i < prices.length; i++) {
            if (i < period) {
                ema[i] = 0.01;
                continue;
            }
            double sum = 0;
            for (int j = 0; j < period; j++) {
                sum += prices[i - j];
            }
            // EMA公式
            ema[i] = sum / period;
        }
        return ema;
    }

    public static void main(String[] args) {
        double[] prices = {/* 实际股票价格数据 */};
        int period = 20; // 举例使用20日均线
        //double[] ema = calculateEMA(prices, period);
        //for (double ma : ema) {
        //    System.out.println(ma);
        //}
    }
}
